﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using RFServer.Functions;

namespace RFServer.Interactive
{
    public partial class InteractiveSetup : Form
    {
        public InteractiveSetup()
        {
            InitializeComponent();

            /* Считываем настройки */

            LoadCurrentCofig();
        }

        private List<char> AviableDrives()
        {
            List<char> usedDrives = new List<char>();
            List<char> availDrives = new List<char>();

            foreach (DriveInfo drive in DriveInfo.GetDrives())
                usedDrives.Add(drive.Name.ToUpperInvariant()[0]);

            for (char c = 'C'; c <= 'Z'; c ++)
                availDrives.Add(c);

            foreach (char c in usedDrives)
                availDrives.Remove(c);

            return availDrives;
        }

        private void LoadCurrentCofig()
        {
            txtLocalService.Text = Setup.ServiceLocalAddress;
            txtMainService.Text = Setup.ServiceMainHost;
            txtPort.Text = Setup.Port.ToString();
            cmbAuth.SelectedIndex = 0;

            txtWorkingDirectory.Text = Setup.WorkingDirectory;
            txtDatabase.Text = Path.GetFileName(Setup.DatabasePathFile);
            txtLog.Text = Path.GetFileName(Setup.LogPathName);
            txtUpload.Text = Setup.UploadDir;

            chkDrive.Checked = Setup.Drive;
            EnableDisableDrive(null, null);

            chkRemoveEmptyTags.Checked = Setup.AutomaticallyRemoveEmptyTags;
            chkLogAdvanced.Checked = Setup.LogAdvanced;
            chkWatcher.Checked = Setup.Watcher;
            chkIntegration.Checked = CheckIntegration();

            chkDropBox.Checked = Setup.DropBoxInUse;
            txtDropBoxDirectory.Text = Setup.DropBoxDirectory;
            EnableDisableDropbox(null, null);

            List<char> availDrives = AviableDrives();

            foreach (char drive in availDrives)
                cmbDrive.Items.Add(drive);
            cmbDrive.Text = Setup.DriveLetter.ToString();
        }

        private void Integrate(object sender, EventArgs e)
        {
            RegistryKey key = Registry.ClassesRoot;

            try
            {
                if (chkIntegration.Checked)
                {
                    key = Registry.ClassesRoot.CreateSubKey("*\\shell\\rfs");
                    key.SetValue("", "Назначить тэги");
                    key = Registry.ClassesRoot.CreateSubKey("*\\shell\\rfs\\command");
                    key.SetValue("", Application.ExecutablePath + " -insert \"%1\"");

                    key = Registry.ClassesRoot.CreateSubKey("Folder\\shell\\rfs");
                    key.SetValue("", "Назначить тэги");
                    key = Registry.ClassesRoot.CreateSubKey("Folder\\shell\\rfs\\command");
                    key.SetValue("", Application.ExecutablePath + " -insert \"%1\"");
                }
                else
                {
                    Registry.ClassesRoot.DeleteSubKeyTree("*\\shell\\rfs");
                    Registry.ClassesRoot.DeleteSubKeyTree("Folder\\shell\\rfs");
                }
            }
            catch (Exception ex)
            {
                Error.Show("Ошибка при записи в реестр", ex);
            }
            finally
            {
                key.Close();
            }
        }

        private bool CheckIntegration()
        {
            RegistryKey key = Registry.ClassesRoot;

            try
            {
                key = Registry.ClassesRoot.OpenSubKey("*\\shell\\rfs");
                return key != null;
            }
            catch (Exception ex)
            {
                return Error.Show("Ошибка при обращении к реестру", ex);
            }
            finally
            {
                if (key != null)
                    key.Close();
            }
        }

        /// <summary>
        /// Сохранение настроек в App.config
        /// </summary>
        
        private void AcceptChanges(object sender, EventArgs e)
        {
            try
            {
                Setup.Port = Int32.Parse(txtPort.Text);
                Setup.LogAdvanced = chkLogAdvanced.Checked;

                if (cmbDrive.Items.Count != 0)
                {
                    Setup.DriveLetter = Char.Parse(cmbDrive.Text);
                    Setup.Drive = chkDrive.Checked;
                }

                Setup.AutomaticallyRemoveEmptyTags = chkRemoveEmptyTags.Checked;
                Setup.Watcher = chkWatcher.Checked;

                Setup.DropBoxInUse = chkDropBox.Checked;
                Setup.DropBoxDirectory = txtDropBoxDirectory.Text;

                Setup.Save();

                Close();
            }
            catch (Exception ex)
            {
                Error.Show("Невозможно сохранить настройки", ex);
            }
        }

        private void BrowseDropBoxDirectory(object sender, EventArgs e)
        {
            try
            {
                if (Browser.ShowDialog() == DialogResult.OK)
                    txtDropBoxDirectory.Text = Browser.SelectedPath;
            }
            catch (Exception ex)
            {
                Error.Show("Невозможно отобразить окно выбора диретории");
                Setup.Log("[setup]: Cannot open browse dialog for DropBox", ex);
            }
        }

        private void EnableDisableDrive(object sender, EventArgs e)
        {
            cmbDrive.Enabled = chkDrive.Checked;
        }

        private void EnableDisableDropbox(object sender, EventArgs e)
        {
            txtDropBoxDirectory.Enabled = chkDropBox.Checked;
            btnBrowseDropBox.Enabled = chkDropBox.Checked;
        }

        private void Cancel(object sender, EventArgs e)
        {
            Close();
        }
    }
}
